package com.lahuan.rpc.protocol.netty.client;

import com.alibaba.fastjson.JSON;
import com.lahuan.rpc.protocol.tcp.RpcfxRequest;
import com.lahuan.rpc.protocol.tcp.RpcfxResponse;

import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.net.URISyntaxException;

public class ClientInvoker<T> implements InvocationHandler {
    private Class<T> type;
    private String host;
    private int port;

    public ClientInvoker(Class<T> type, String host, int port){
        this.type = type;
        this.host = host;
        this.port = port;
    }

    private RpcfxResponse post(RpcfxRequest req) throws IOException, URISyntaxException, InterruptedException {
        String reqJson = JSON.toJSONString(req);

        System.out.println("req : "+reqJson);

        String respJson = NettyClient.getResponse(host,port, reqJson);
        System.out.println("resp : "+respJson);
        return  JSON.parseObject(respJson,RpcfxResponse.class);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("client invoke");
        RpcfxRequest request = new RpcfxRequest();
        request.setServiceClass(type.getName());
        request.setMethod(method.getName());
        request.setParams(args);
        RpcfxResponse response = post(request);
        Class<?> returnType = method.getReturnType();

        return JSON.parseObject(JSON.toJSONString(response.getResult()),returnType);
    }
}
